<template>
  <div v-loading="!isShowPage">
    <!-- control -->
    <div class="header">
      <el-button
        class="primary-plain-btn"
        type="primary"
        round
        size="mini"
        plain
        @click="handleSmartSetting"
        :disabled="isTableLoading"
        >智能设置</el-button
      >
      <div class="fr">
        <el-popover placement="bottom-end" width="720" trigger="hover" :open-delay="300">
          <div class="lhxl">
            <div>1、自动编辑：针对安居客模拟人工手动修改房源，并且不影响正常的房源信息</div>
            <div>2、三网规定编辑日期超过30天的房源将自动下架，使用该功能可以避免房源被下架</div>
            <div>3、每晚凌晨是各个网站的系统维护时间，建议不要添加这个时间段的时间点，如：23:58、00:01、00:03</div>
            <div>
              4、当天添加的时间点，已经过去的时间从明天才开始执行，比如：现在是下午15:00，添加的15：00点之前的时间点当天不会执行
            </div>
          </div>
          <el-button type="text" slot="reference" size="mini"
            >使用说明<i class="el-icon-question el-icon--right"></i
          ></el-button>
        </el-popover>
      </div>
    </div>
    <!-- table -->
    <template v-if="isNonEmptyTable">
      <el-table
        v-loading="isTableLoading"
        ref="table"
        class="table"
        :data="tableData"
        :row-class-name="({ row, rowIndex }) => (rowIndex % 2 === 0 ? '' : 'cell-bg')"
        header-cell-class-name="header-cell-bg"
        height="350"
        size="mini"
        @selection-change="handleTableSelectChange"
      >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column
          v-for="item in tableOptions"
          :key="item.id"
          :label="item.label"
          :prop="item.prop"
          :width="item.width"
          :min-width="item.minWidth"
        >
          <template slot-scope="{ row }">
            <template v-if="item.prop">
              <span>{{ row[item.prop] }}</span>
            </template>

            <template v-if="item.id === 'TABLE_EXECUTE_TIME'">
              <span class="text-blue">{{ row.refreshTime }}</span>
            </template>

            <template v-if="item.id === 'TABLE_STATUS'">
              <el-tag
                v-if="row.status && taskStatusOptins[row.status]"
                size="mini"
                effect="dark"
                :type="taskStatusOptins[row.status].color"
                >{{ taskStatusOptins[row.status].text }}</el-tag
              >
            </template>

            <template v-if="item.id === 'TABLE_COUNT'">
              <span>自动刷新{{ row.count || 1 }}套</span>
            </template>

            <template v-if="item.id === 'TABLE_ADD_TIME'">
              <span>{{ row.updateTime }}</span>
            </template>

            <template v-if="item.id === 'TABLE_CONTROL'">
              <el-button class="mr10" size="mini" type="text" @click="handleEdit(row.refreshTime, row.id)"
                >修改</el-button
              >
              <el-popconfirm hide-icon title="确定要删除吗？" @confirm="handleDel(row.id)">
                <el-button slot="reference" class="text-red" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-else>
      <div class="table-empty">
        <el-result v-show="isShowPage" icon="success" title="您还未设置时间点">
          <template slot="icon">
            <el-image :src="require('@/assets/images/port_refresh_log@1x.png')"></el-image>
          </template>
          <template slot="extra">
            <el-button type="primary" size="medium" round @click="handleSmartSetting" :disabled="isTableLoading"
              >智能生成时间点</el-button
            >
          </template>
        </el-result>
      </div>
    </template>
    <!-- bottom control -->
    <div class="control">
      <div>
        <el-button type="text" round size="mini" v-if="isNonEmptyTable" @click="handleSelectAll">全选</el-button>
        <el-popconfirm v-if="isNonEmptyTable" hide-icon title="确定要删除已勾选的吗？" @confirm="handleDelAll">
          <el-button slot="reference" type="text" round size="mini" :disabled="isBanDel">删除</el-button>
        </el-popconfirm>
      </div>
      <div>
        <el-button type="primary" round size="mini" @click="handleBack">返回选择类型</el-button>
        <el-button type="primary" round size="mini" @click="handleClose">关闭</el-button>
      </div>
    </div>
    <!-- edit dialog -->
    <el-dialog class="dialog-radius" width="400px" title="修改时间点" :visible.sync="isShowEditDialog" append-to-body>
      <div v-if="isShowEditDialog">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="时间点" prop="time">
            <el-time-picker
              v-model="form.time"
              :picker-options="{
                selectableRange: '08:00:00 - 22:00:00'
              }"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="选择时间点"
              size="mini"
            >
            </el-time-picker>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handleConfirm('form')" round :loading="isSaveLoading"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { validTimePoint } from '@/utils/validate';

export default {
  name: 'RefreshTime',

  components: {},

  filters: {},

  inject: {
    rootPort: {
      default() {
        return {};
      }
    }
  },

  props: {
    currentSetting: {
      type: Object,
      default() {
        return {};
      }
    }
  },

  data() {
    this.tableOptions = [
      { id: 'TABLE_EXECUTE_TIME', label: '执行时间', width: '100' },
      { id: 'TABLE_STATUS', label: '执行状态', width: '120' },
      { id: 'TABLE_COUNT', label: '刷新次数', width: '130' },
      { id: 'TABLE_ADD_TIME', label: '操作时间', minWidth: '120' },
      { id: 'TABLE_CONTROL', label: '操作', width: '100' }
    ];
    this.taskStatusOptins = {
      '0': {
        color: 'info',
        text: '未开启'
      },
      '1': {
        color: 'success',
        text: '开启中'
      },
      '2': {
        color: 'danger',
        text: '已停止'
      }
    };
    this.currentPoints = [];
    const validateRepeat = (rule, value, callback) => {
      if (this.currentPoints.indexOf(value) !== -1) {
        callback(new Error('时间点不能重复'));
      } else {
        callback();
      }
    };

    return {
      isSaveLoading: false,
      isShowPage: false,
      isTableLoading: false,
      form: {
        time: '',
        id: ''
      },
      rules: {
        time: [
          { required: true, message: '时间点不能为空', trigger: 'change' },
          { pattern: validTimePoint, message: '时间点格式必须为00:00', trigger: 'change' },
          { validator: validateRepeat, trigger: 'change' }
        ]
      },
      isShowEditDialog: false,
      tableData: [],
      currentSelect: []
    };
  },

  computed: {
    isNonEmptyTable() {
      const { tableData } = this;
      return tableData && tableData.length;
    },
    isBanDel() {
      return !(this.currentSelect && this.currentSelect.length);
    }
  },

  watch: {},

  beforeMount() {},

  mounted() {
    this.loadSettingPoints();
  },

  methods: {
    // ------------------handle------------------
    handleBack() {
      this.$emit('back');
    },
    handleClose() {
      this.$emit('close');
    },
    handleEdit(time, id) {
      this.form.time = time;
      this.form.id = id;
      this.isShowEditDialog = true;
    },
    handleDel(id) {
      this.delTime([id]);
    },
    handleDelAll() {
      this.delTime(
        this.currentSelect.map((item) => {
          return item.id;
        })
      );
    },
    handleSmartSetting() {
      this.smartSetting();
    },
    handleSelectAll() {
      this.$refs.table.toggleAllSelection();
    },
    handleTableSelectChange(e) {
      this.currentSelect = e;
    },
    // 保存编辑
    handleConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.editTime();
        } else {
          return false;
        }
      });
    },
    // ------------------function------------------
    async editTime() {
      try {
        this.isSaveLoading = true;
        const { time, id } = this.form;
        const res = await this.$api.updateAutoRefreshDetail({
          id,
          refreshTime: time
        });
        if (res && res.isSuccess) {
          this.loadSettingPoints();
          this.isShowEditDialog = false;
          this.$message.success('修改成功~');
        } else {
          this.$message.error('修改失败，请稍后再试~');
        }
      } catch (error) {
        console.log('error', error);
      } finally {
        this.isSaveLoading = false;
      }
    },
    async delTime(id) {
      try {
        if (!(id && id.length)) {
          return;
        }
        const res = await this.$api.deleteAutoRefreshDetail(id);
        if (res && res.isSuccess) {
          this.loadSettingPoints();
          this.$message.success('删除成功~');
        } else {
          this.$message.error('删除失败，请稍后再试~');
        }
      } catch (error) {
        console.log('error', error);
      }
    },
    async loadSettingPoints() {
      try {
        const { id, type } = this.currentSetting;
        if (!id) {
          return;
        }
        this.isTableLoading = true;
        let res = await this.$api.getAutoRefreshDetailList({
          id
        });
        this.tableData = res.content || [];
        this.currentPoints = res.content.map((item) => {
          return item.refreshTime;
        });
      } catch (error) {
        console.log('error', error);
      } finally {
        this.isShowPage = true;
        this.isTableLoading = false;
      }
    },
    async smartSetting() {
      try {
        this.isTableLoading = true;
        const { id, type } = this.currentSetting;
        let res = await this.$api.autoRefreshConfig({
          userPortId: this.rootPort.portInfo.id,
          delegationType: type
        });
        if (res && res.isSuccess) {
          this.tableData = res.content || [];
          this.currentSetting.id = res.content[0].autoRefreshInfoId || '';
          this.currentPoints = res.content.map((item) => {
            return item.refreshTime;
          });
          this.$message.success('成功生成了48个时间点~');
        }
      } catch (error) {
        console.log('error', error);
      } finally {
        this.isTableLoading = false;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import '~@/styles/colors.scss';
@import '~@/styles/mixin.scss';

.header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
}

.table {
  & /deep/ .header-cell-bg {
    background: $light-blue;
  }

  & /deep/ .cell-bg {
    background: $lightest-blue;
  }

  & /deep/ td {
    border-bottom: none;
  }

  &::before {
    height: 0;
  }

  & /deep/ .el-table__body-wrapper {
    @include scrollBar;
  }

  & /deep/ .el-table__header .el-table-column--selection .cell {
    display: none;
  }
}

.table-empty {
  height: 408px;
}

.control {
  position: absolute;
  left: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  width: 100%;
  height: 50px;
}

.dialog-radius /deep/ .el-dialog {
  border-radius: 16px;
}
</style>
